using System;
using System.Data;
using System.Collections;
using APP.QUANLY.Entity;
using APP.QUANLY.Entity.ConditionForm;

namespace APP.QUANLY.DAL
{
    /// <summary>
    /// Summary description for KHO.
     /// </summary>
	public class KHODao
    {
	    private string _SQLSelectByKey;
	    private string _SQLUpdate;
	    private string _SQLInsert;
	    private string _SQLDelete;
	    private string _SQLSelectAll;

        #region Properties

        public IDbConnection _dbConnection;

        public IDbConnection DbConnection
        {
            get { return _dbConnection; }
            set { _dbConnection = value; }
        }

        #endregion
        
        #region Constructor

        public KHODao()
        {
            _dbConnection = null;
		    InitSqlQuery();
        }

        public KHODao(IDbConnection con)
        {
            _dbConnection = con;
            InitSqlQuery();
        }

        #endregion


        private void ToLowerQuery()
        {
            _SQLDelete = _SQLDelete.ToLower();
            _SQLUpdate = _SQLUpdate.ToLower();
            _SQLInsert = _SQLInsert.ToLower();
            _SQLSelectByKey = _SQLSelectByKey.ToLower();
        }

        private void ToUpperQuery()
        {
            _SQLDelete = _SQLDelete.ToUpper();
            _SQLUpdate = _SQLUpdate.ToUpper();
            _SQLInsert = _SQLInsert.ToUpper();
            _SQLSelectByKey = _SQLSelectByKey.ToUpper();
        }

        #region InitSqlQuery
        private void InitSqlQuery()
       {
            string query;

            query = @"SELECT MAKHO, MACODE, TENKHO, DIACHI, ISUSE, KHOMACDINH, GHICHU FROM KHO WHERE (MAKHO = @MAKHO)";
	        _SQLSelectByKey = query;

            query = @"UPDATE KHO SET MACODE = @MACODE, TENKHO = @TENKHO, DIACHI = @DIACHI, ISUSE = @ISUSE, KHOMACDINH = @KHOMACDINH, GHICHU = @GHICHU WHERE (MAKHO = @MAKHO)";
	        _SQLUpdate = query;

            query = @"INSERT INTO KHO VALUES (@MAKHO, @MACODE, @TENKHO, @DIACHI, @ISUSE, @KHOMACDINH, @GHICHU)";
	        _SQLInsert = query;

            query = @"DELETE FROM KHO WHERE (MAKHO = @MAKHO)";
	        _SQLDelete = query;

            query = @"SELECT MAKHO, MACODE, TENKHO, DIACHI, ISUSE, KHOMACDINH, GHICHU FROM KHO";
	        _SQLSelectAll = query;
        }
        #endregion
        public void LoadByCommandText(string commandtext, IDbTransaction trans)
        {
            if (_dbConnection == null)
            {
                throw new Exception("Connection has not been set.");
            }

            IDbCommand command;

            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }

                command = _dbConnection.CreateCommand();
                command.CommandText = commandtext;

				if (trans != null) { command.Transaction = trans; }
                if (command.ExecuteNonQuery() == 0) { throw new Exception("Zero rows were affected."); }
            }
            catch (Exception ex) { throw ex; }
        }

        #region Save & Delete
        private void Save(KHO obj, IDbTransaction trans, bool isExisting)
        {
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }

            IDbCommand command;

            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                command = _dbConnection.CreateCommand();

                if (!isExisting) { command.CommandText = _SQLInsert + ";"; }
                else { command.CommandText = _SQLUpdate + ";"; }

                         DalTools.addDbDataParameter(command, "MAKHO", obj.MAKHO, DbType.Guid);
                         DalTools.addDbDataParameter(command, "MACODE", obj.MACODE, DbType.String);
         DalTools.addDbDataParameter(command, "TENKHO", obj.TENKHO, DbType.String);
         DalTools.addDbDataParameter(command, "DIACHI", obj.DIACHI, DbType.String);
         DalTools.addDbDataParameter(command, "ISUSE", obj.ISUSE, DbType.Boolean);
         DalTools.addDbDataParameter(command, "KHOMACDINH", obj.KHOMACDINH, DbType.Boolean);
         DalTools.addDbDataParameter(command, "GHICHU", obj.GHICHU, DbType.String);

		        if (trans != null) { command.Transaction = trans; }
                if (command.ExecuteNonQuery() == 0) { throw new Exception("Zero rows were affected."); }
            }
            catch (Exception ex) { throw ex; }
        }

        public void Delete(KHO obj, IDbTransaction trans)
        {
            if (_dbConnection == null)
            {
                //throw new DalException("Connection has not been set.");
                throw new Exception("Connection has not been set.");
            }

            IDbCommand command;

            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }

                command = _dbConnection.CreateCommand();
                command.CommandText = _SQLDelete + ";";

                         DalTools.addDbDataParameter(command, "MAKHO", obj.MAKHO, DbType.Guid);

		        if (trans != null) { command.Transaction = trans; }
                if (command.ExecuteNonQuery() == 0) { throw new Exception("Zero rows were affected."); }
            }
            catch (Exception ex) { throw ex; }
        }

        public void Insert(KHO obj, IDbTransaction trans)
        {
            Save(obj, trans, false);
        }
        public void Update(KHO obj, IDbTransaction trans)
        {
            Save(obj, trans, true);
        }
        #endregion

        #region Command Execute & Read Properties
     
        private KHOList SelectListByCommand(IDbCommand command)
        {
            KHOList list = new KHOList();
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }
            try
            {	
				KHO obj;
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                using (IDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read()) 
					{ 
						obj = new KHO();
						ReadProperties(obj, reader);
						list.Add(obj); 
					}
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list;
        }
		
        private KHOList SelectListByCommand(IDbCommand command, IDbTransaction trans)
        {
            KHOList list = new KHOList();
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }
            try
            {	
				KHO obj;
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
				command.Transaction = trans;
                using (IDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read()) 
					{ 
						obj = new KHO();
						ReadProperties(obj, reader);
						list.Add(obj); 
					}
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list;
        }

        private void DeleteListByCommand(IDbCommand command, IDbTransaction trans)
        {
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }
            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                if (trans != null) { command.Transaction = trans; }
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
	
        private void ReadProperties(KHO obj, IDataReader reader)
        {
            try
            {
                                if(!(reader["MAKHO"] is DBNull))
		{
			obj.MAKHO = (Guid)reader["MAKHO"];
		}
                if(!(reader["MACODE"] is DBNull))
		{
			obj.MACODE = (string)reader["MACODE"];
		}
                if(!(reader["TENKHO"] is DBNull))
		{
			obj.TENKHO = (string)reader["TENKHO"];
		}
                if(!(reader["DIACHI"] is DBNull))
		{
			obj.DIACHI = (string)reader["DIACHI"];
		}
                if(!(reader["ISUSE"] is DBNull))
		{
			obj.ISUSE = (bool)reader["ISUSE"];
		}
                if(!(reader["KHOMACDINH"] is DBNull))
		{
			obj.KHOMACDINH = (bool)reader["KHOMACDINH"];
		}
                if(!(reader["GHICHU"] is DBNull))
		{
			obj.GHICHU = (string)reader["GHICHU"];
		}
            }
            catch (Exception ex)
            {
                throw new DalException("Failed to read properties from DataReader.", ex);
            }
        }
        #endregion
      
        public KHO SelectByKey(Guid MAKHO)
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            command.CommandText = _SQLSelectByKey;
	                 DalTools.addDbDataParameter(command, "MAKHO", MAKHO, DbType.Guid);
      	    KHOList list =  SelectListByCommand(command);

            if (list.Count == 0) { throw new Exception("No data was returned"); }
            return list[0];
        }

        public KHO SelectByKey(Guid MAKHO, IDbTransaction trans)
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            command.CommandText = _SQLSelectByKey;
	                 DalTools.addDbDataParameter(command, "MAKHO", MAKHO, DbType.Guid);
      	    KHOList list =  SelectListByCommand(command, trans);
			
            if (list.Count == 0) { throw new Exception("No data was returned"); }
            return list[0];
        }
		
        public KHOList SelectAll()
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            command.CommandText = _SQLSelectAll;
      	    KHOList list =  SelectListByCommand(command);
	        return list;
        }

         public KHOList SelectByCommand(string Command)
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            command.CommandText = Command;
      	    KHOList list =  SelectListByCommand(command);
	        return list;
        }

        public KHOList SelectByCondition(KHOConditionForm condt)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            command.CommandText = "SELECT * FROM KHO " + GetCondtionQuery(condt) + ";";
            FillParamToCommand(command, condt);
            KHOList list = SelectListByCommand(command);
            return list;
        }

        private void DeleteByCondition(KHOConditionForm condt, IDbTransaction trans)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            command.CommandText = "DELETE FROM KHO " + GetCondtionQuery(condt) + ";";
            FillParamToCommand(command, condt);
            DeleteListByCommand(command, trans);
        }

        #region Make Condition Query & Fill Param from Condition to Command
        private string GetCondtionQuery(KHOConditionForm obj)
        {
            if (obj == null) { return ""; }
            string s = "";
            	if (obj.IsSetMAKHO)
	{
    	    s += " AND MAKHO = @MAKHO ";
	}
	if (obj.IsSetMACODE)
	{
    	    s += " AND MACODE = @MACODE ";
	}
	if (obj.IsSetTENKHO)
	{
    	    s += " AND TENKHO = @TENKHO ";
	}
	if (obj.IsSetDIACHI)
	{
    	    s += " AND DIACHI = @DIACHI ";
	}
	if (obj.IsSetISUSE)
	{
    	    s += " AND ISUSE = @ISUSE ";
	}
	if (obj.IsSetKHOMACDINH)
	{
    	    s += " AND KHOMACDINH = @KHOMACDINH ";
	}
	if (obj.IsSetGHICHU)
	{
    	    s += " AND GHICHU = @GHICHU ";
	}
            if (s.Length > 0)
            {
                s =" WHERE "+s.Substring(4);
                return s;
            }
            return "";
        }

        private void FillParamToCommand(IDbCommand command, KHOConditionForm obj)
        {
	    if (obj == null) { return;}
            	            if (obj.IsSetMAKHO)
            {
            	DalTools.addDbDataParameter(command, "MAKHO", obj.MAKHO, DbType.Guid); 
            }
            if (obj.IsSetMACODE)
            {
            	DalTools.addDbDataParameter(command, "MACODE", obj.MACODE, DbType.String); 
            }
            if (obj.IsSetTENKHO)
            {
            	DalTools.addDbDataParameter(command, "TENKHO", obj.TENKHO, DbType.String); 
            }
            if (obj.IsSetDIACHI)
            {
            	DalTools.addDbDataParameter(command, "DIACHI", obj.DIACHI, DbType.String); 
            }
            if (obj.IsSetISUSE)
            {
            	DalTools.addDbDataParameter(command, "ISUSE", obj.ISUSE, DbType.Boolean); 
            }
            if (obj.IsSetKHOMACDINH)
            {
            	DalTools.addDbDataParameter(command, "KHOMACDINH", obj.KHOMACDINH, DbType.Boolean); 
            }
            if (obj.IsSetGHICHU)
            {
            	DalTools.addDbDataParameter(command, "GHICHU", obj.GHICHU, DbType.String); 
            }
        }
        #endregion
    }
}